/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.codeminer.parts.server.users;

import org.codeminer.database.DatabaseException;
import org.codeminer.database.DatabaseManager;
import org.codeminer.parts.application.ApplicationContext;
import org.codeminer.parts.application.ShutdownCallback;
import org.codeminer.parts.database.UserConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;

/**
 * @author Daniel Wasilew <daniel.wasilew@codeminer.org>
 */
public class DatabaseUserManager extends AbstractUserManager {

    private static final Logger log = LoggerFactory.getLogger(DatabaseUserManager.class);
    private ApplicationContext applicationContext;

    @Override
    public User register(String name, String passwordHash) throws DuplicatedUserException, UserCreationException {
        if (name == null || passwordHash == null) {
            throw new IllegalArgumentException("name or password is null");
        }

        if (passwordHash.length() != 128) {
            throw new IllegalArgumentException("you should only store sha512 hashed passwords");
        }

        try {
            checkUserExists(name);
        } catch (DatabaseException e) {
            throw new UserCreationException(e);
        }

        User user = new User(name);
        try {
            getUserConnector().storeUser(user, passwordHash);
        } catch (DatabaseException ex) {
            throw new UserCreationException(ex);

        }
        return user;
    }

    private void checkUserExists(String name) throws DatabaseException, DuplicatedUserException {
        try {
            getUserConnector().getUser(name);
            throw new DuplicatedUserException();
        } catch (DatabaseException ex) {
            if (!ex.getMessage().startsWith("no user with name")) {
                throw ex;
            }
        }
    }

    private UserConnector getUserConnector() throws DatabaseException {
        return applicationContext.getApplicationPart(DatabaseManager.class).getConnector(UserConnector.class);
    }

    @Override
    public User login(String name, String passswordHash) throws LoginException {
        User user = getUser(name);
        try {
            String storedPass = getUserConnector().getUserPassword(user);
            if (storedPass != null && storedPass.equals(passswordHash)) {
                super.loggedIN(user);
                return user;
            } else {
                throw new LoginException("could not find user");
            }
        } catch (DatabaseException ex) {
            throw new LoginException("could not find user");
        }
    }

    @Override
    public User getUser(String name) throws LoginException {
        try {
            return getUserConnector().getUser(name);
        } catch (DatabaseException e) {
            throw new LoginException("could not find user");
        }

    }

    @Override
    public void delete(User user) {
        try {
            getUserConnector().deleteUser(user);
        } catch (DatabaseException ex) {
            log.error("could not delete user", ex);
        }
    }

    @Override
    public List<User> getAllUsers() {
        try {
            return getUserConnector().getUsers();
        } catch (DatabaseException ex) {
            log.error("could not get users from db", ex);
            return Collections.emptyList();
        }
    }

    @Override
    protected void startUpCalled(ApplicationContext context, ShutdownCallback shutdownCallback) {
        this.applicationContext = context;
    }

    @Override
    protected void shutdownCalled() {
    }
}
